<?php

namespace app\admin\controller;

use app\common\Helper;

use app\admin\model\Menu;
use app\admin\model\Operator;
use app\admin\model\Roleuser;

use think\Exception;
use think\Request;

class Role extends Base
{

    public function getlist(){
        $params = $this->request->param();
        $where = [];
        if(isset($params['name']) && $params['name']){
            $where['name'] = ['like', "%{$params['name']}%"];
        }

        $model = model('Role');
        $list = $model->where($where)->paginate(10);
        $total = $model->where($where)->count();

        return $this->fetch('',[
            'datas' => $list,
            'total' => $total,
            'formget' => $_GET
        ]);
    }

    public function add(){
        // 权限列表
        //$rules = $this->menuJson();
        $rules = Menu::where(['status' => 1])->order('sorting', 'ASC')->select();

        $this->assign('rules', $rules);

        return $this->fetch();
    }

    public function edit(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return show(config('status.error_code'),'缺少参数','缺少参数');
        }
        $model = model('Role');
        $info = $model->get($param['id']);
        $info['access'] = explode(',', $info['access']);

        // 权限列表
        //$rules = $this->menuJson();
        $rules = Menu::where(['status' => 1])->order('sorting', 'ASC')->select();

        $this->assign('rules', $rules);

        return $this->fetch('',[
            'info' => $info
        ]);
    }

    public function savePost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            $model = model('Role');

            if(empty($param['name'])){
                return show(config('status.error_code'),'缺少参数','缺少参数');
            }
            if(!empty($param['ruleIds'])){
                $param['access'] = implode(',', $param['ruleIds']);
            }
            $data = $param;
            if(empty($param['id'])){
                // 新增
                $data['id'] = Helper::getUUID();
                $data['createDate'] = date('Y-m-d H:i:s');
                $data['createOper'] = $this->admin->id;

                $result = $model->save($data);
            }else{
                // 修改
                $data['id'] = $param['id'];
                $data['updateDate'] = date('Y-m-d H:i:s');
                $data['updateOper'] = $this->admin->id;

                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            }

            if($result !== false){
                return show(config('status.success_code'),'保存成功','保存成功');
            }else{
                return show(config('status.error_code'),'保存失败','保存失败');
            }
        }else{
            return show(config('status.error_code'),'请求不合法','请求不合法');
        }
    }

    /**
     * 启用/禁用
     */
    public function handle(){
        $param = $this->request->param();
        $model = model('Role');

        $id = $param['id'];
        if($param['type'] == 1){
            // 启用
            $data['status'] = 1;
            $result = $model->allowField(true)->save($data, ['id' => $id]);
        }else{
            // 禁用
            // 检查该角色是否已有管理员
            if(!$this->checkRoleuser($id)){
                return show(config('status.error_code'),'该角色已有管理员，不能禁用','该角色已有管理员，不能禁用');
            }

            $data['status'] = 2;
            $result = $model->allowField(true)->save($data, ['id' => $id]);
        }

        if($result !== false){
            return show(config('status.success_code'), '操作成功', '操作成功');
        }else{
            return show(config('status.error_code'), '操作失败', $model->getError());
        }
    }

    /**
     * 删除
     */
    public function del(Request $request){
        $model = model($this->model);
        if($request->isPost()){
            //$param = $request->param();
            $id = $request->param('id');

            try {
                // 检查该角色是否已有管理员
                if(!$this->checkRoleuser($id)){
                    return show(config('status.error_code'),'该角色已有管理员，不能删除','该角色已有管理员，不能删除');
                }

                $result = $model->where('id', $id)->update(['status' => 2]);

                if($result === false){
                    return show(config('status.error_code'),'删除失败','删除失败');
                }

                return show(config('status.success_code'),'删除成功','删除成功');
            } catch (Exception $e) {
                return show(config('status.error_code'), '删除失败', $e->getMessage());
            }
        }
    }

    /**
     * 检查角色是否已有管理员
     */
    private function checkRoleuser($roleId){
        // 判断该角色是否已有管理员
        $operatorId = Roleuser::where('roleId', $roleId)->find();
        if($operatorId){
            return false;
        }

        return true;
    }

}